<template>
  <view class="container">
    <!-- 页面主体内容 -->
    <view class="content-area">
      <!-- 分类列表 -->
      <view class="category-list">
        <template v-for="(item, index) in localCategoryList">
          <view
            :key="`item-${index}`"
            :id="`category-item-${index}`"
            class="category-item"
            :class="{
              fixed: item.fixed,
              dragging: dragIndex === index && isEditMode,
              protected: item.protected,
            }"
            :style="[
              dragIndex === index && isEditMode
                ? {
                    opacity: '0.8',
                    transform: `translateY(${dragCurrentY}px)`,
                    zIndex: 10,
                    boxShadow: '0 4rpx 12rpx rgba(0, 0, 0, 0.1)',
                  }
                : {},
            ]"
          >
            <view class="category-content">
              <!-- 在编辑模式下显示拖拽图标，非编辑模式不显示 -->
              <view
                class="drag-icon"
                v-if="isEditMode && !item.fixed"
                @touchstart.stop="onDragStart($event, index)"
                @touchmove.stop.prevent="onDragMove($event)"
                @touchend.stop="onDragEnd"
              >
                <text class="drag-handle">≡</text>
              </view>

              <!-- 分类图标始终显示 -->
              <view class="category-icon">
                <image :src="item.iconPath" mode="aspectFit"></image>
              </view>

              <!-- 分类名称 -->
              <text class="category-text">{{ item.text }}</text>
            </view>

            <!-- 编辑模式下的操作按钮 -->
            <view v-if="isEditMode" class="action-buttons">
              <view
                class="btn-delete"
                @click="deleteCategory(index)"
                v-if="!item.fixed && !item.protected"
              >
                <text>×</text>
              </view>
              <view
                class="edit-btn-small"
                @click="editCategory(index)"
                v-if="!item.fixed"
              >
                <text class="edit-icon">✎</text>
              </view>
            </view>
          </view>

          <!-- 编辑表单，显示在当前编辑的分类项下方 -->
          <view
            v-if="isAddingNew && isEditing && editingIndex === index"
            :key="`edit-form-${index}`"
            :id="`edit-form-${index}`"
            class="inline-edit-form"
          >
            <view class="add-form">
              <input
                class="category-input"
                v-model="newCategoryName"
                placeholder="请输入分类名称"
                focus
                @blur="handleInputBlur"
              />

              <!-- 图标选择区域 -->
              <view class="icon-selector">
                <text class="selector-title">选择图标</text>
                <view class="icon-grid">
                  <view
                    v-for="(icon, idx) in availableIcons"
                    :key="idx"
                    class="icon-item"
                    :class="{ selected: selectedIconIndex === idx }"
                    @click="selectIcon(idx)"
                  >
                    <image :src="getIconPath(icon)" mode="aspectFit"></image>
                  </view>
                </view>
              </view>

              <view class="form-actions">
                <view class="btn-cancel" @click="cancelAdd">取消</view>
                <view class="btn-confirm" @click="confirmAdd">确定</view>
              </view>
            </view>
          </view>
        </template>
      </view>

      <!-- 添加新分类按钮和表单（只在编辑模式下显示，且不是正在编辑某个分类时） -->
      <view class="add-category" v-if="isEditMode && !isEditing">
        <view v-if="isAddingNew" class="add-form">
          <input
            class="category-input"
            v-model="newCategoryName"
            placeholder="请输入分类名称"
            focus
            @blur="handleInputBlur"
          />

          <!-- 图标选择区域 -->
          <view class="icon-selector">
            <text class="selector-title">选择图标</text>
            <view class="icon-grid">
              <view
                v-for="(icon, idx) in availableIcons"
                :key="idx"
                class="icon-item"
                :class="{ selected: selectedIconIndex === idx }"
                @click="selectIcon(idx)"
              >
                <image :src="getIconPath(icon)" mode="aspectFit"></image>
              </view>
            </view>
          </view>

          <view class="form-actions">
            <view class="btn-cancel" @click="cancelAdd">取消</view>
            <view class="btn-confirm" @click="confirmAdd">确定</view>
          </view>
        </view>
        <view v-else class="btn-add" @click="startAddNew">
          <text class="add-icon">+</text>
          <text class="add-text">添加新分类</text>
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="tip-section">
        <text class="tip-text">
          提示:
          "全部任务"为固定分类不可编辑，标记为"默认"的分类可以修改但不能删除，其他分类可以随意修改和删除,长按 ≡ 拖动进行排序。
        </text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view v-if="!isEditMode" class="action-buttons">
        <app-button
          type="secondary"
          size="lg"
          class="bottom-btn "
          @click="goBack"
          >返回</app-button
        >
        <app-button
          type="primary"
          size="lg"
          class="bottom-btn "
          @click="toggleEditMode"
          >编辑</app-button
        >
      </view>
      <view v-if="isEditMode" class="action-buttons">
        <app-button
          type="secondary"
          size="lg"
          class="bottom-btn "
          @click="cancelEditMode"
          >取消</app-button
        >
        <app-button
          type="primary"
          size="lg"
          class="bottom-btn"
          @click="saveAndExitEditMode"
          >保存</app-button
        >
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapGetters, mapActions } from "vuex";
import { getIconPath } from "@/utils/iconUtils";
import AppButton from "@/components/common/AppButton.vue";

export default {
  name: "CategoryEdit",
  components: {
    AppButton,
  },
  data() {
    return {
      isAddingNew: false,
      newCategoryName: "",
      hasChanges: false,
      isEditMode: false,
      isEditing: false, // 是否是编辑已有分类
      editingIndex: -1, // 正在编辑的分类索引

      // 可选图标列表 - 只存储图标名称
      availableIcons: Array.from({ length: 23 }, (_, i) => `e${i + 10}`),
      selectedIconIndex: 0,

      // 拖拽相关
      dragIndex: -1,
      dragStartY: 0,
      dragCurrentY: 0,
      itemHeight: 0,

      // 本地缓存原始分类列表
      originalCategories: [],
      // 本地修改的分类列表（未保存到Vuex）
      localCategoryList: null,
    };
  },
  computed: {
    ...mapGetters("categories", ["getAllCategories"]),
  },
  onLoad() {
    // 确保分类数据已初始化
    if (!this.getAllCategories || this.getAllCategories.length === 0) {
      console.log("分类数据为空，初始化默认数据");
      this.$store.dispatch("categories/initCategories");
    }

    console.log("Vuex中的分类数据:", this.getAllCategories);

    // 使用nextTick确保Vuex数据已更新
    this.$nextTick(() => {
      // 初始化本地分类数据
      this.localCategoryList = this.getAllCategories.map((category) => ({
        ...category,
        iconPath: this.getIconPath(category.icon),
        // 确保protected属性被保留
        protected: category.protected || false,
        fixed: category.fixed || false,
      }));

      console.log("初始化后的本地分类列表:", this.localCategoryList);

      // 保存原始副本用于取消操作
      this.originalCategories = JSON.parse(
        JSON.stringify(this.localCategoryList)
      );
    });
  },
  methods: {
    ...mapActions("categories", ["saveCategories", "setActiveCategory"]),

    // 获取图标完整路径
    getIconPath(iconName) {
      if (!iconName) return "";
      try {
        return require(`@/static/icons/icon_umlcd901z/${iconName}.png`);
      } catch (error) {
        console.error("Failed to load icon:", iconName, error);
        return ""; // 返回空字符串作为替代
      }
    },
    // 进入编辑模式前，保存原始数据
    toggleEditMode() {
      this.originalCategories = JSON.parse(
        JSON.stringify(this.localCategoryList)
      );
      this.isEditMode = true;

      // 重置添加和编辑状态
      this.isAddingNew = false;
      this.isEditing = false;
      this.editingIndex = -1;
    },
    // 取消编辑，恢复原始数据
    cancelEditMode() {
      this.localCategoryList = JSON.parse(
        JSON.stringify(this.originalCategories)
      );
      this.isEditMode = false;
      this.isAddingNew = false;
      this.isEditing = false;
      this.editingIndex = -1;
      this.dragIndex = -1;
      this.hasChanges = false;
      uni.showToast({
        title: "已取消编辑",
        icon: "none",
        duration: 1500,
      });
    },
    // 使用Vuex保存分类数据
    saveAndExitEditMode() {
      // 打印本地分类列表，检查是否包含新增的分类
      console.log("保存前的localCategoryList:", this.localCategoryList);

      // 使用Vuex保存分类数据
      const categoriesToSave = this.localCategoryList.map((category) => ({
        id: category.id,
        text: category.text,
        fixed: category.fixed || false,
        protected: category.protected || false,
        icon: category.icon,
      }));

      console.log("准备保存到Vuex的分类数据:", categoriesToSave);

      // 提交到Vuex
      this.saveCategories(categoriesToSave);
      this.isEditMode = false;
      this.hasChanges = false;

      // 触发全局事件，通知其他页面数据已更新
      // 确保发送的是不带iconPath的数据，与Vuex中的格式一致
      uni.$emit("update-categories", categoriesToSave);

      uni.showToast({
        title: "保存成功",
        icon: "success",
        duration: 1500,
      });

      // 短暂延迟后返回上一页，确保数据已同步
      // setTimeout(() => {
      //   uni.navigateBack();
      // }, 1000);
    },

    goBack() {
      if (this.hasChanges) {
        uni.showModal({
          title: "提示",
          content: "您有未保存的更改，确定要离开吗？",
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack();
            }
          },
        });
      } else {
        uni.navigateBack();
      }
    },

    deleteCategory(index) {
      const categoryToDelete = this.localCategoryList[index];

      // 检查是否为固定分类或受保护分类
      if (categoryToDelete.fixed || categoryToDelete.protected) {
        uni.showToast({
          title: categoryToDelete.fixed
            ? "固定分类不能删除"
            : "默认分类不能删除",
          icon: "none",
          duration: 1500,
        });
        return;
      }

      uni.showModal({
        title: "提示",
        content: "确定要删除此分类吗？",
        success: (res) => {
          if (res.confirm) {
            // 本地删除，保存时才同步到Vuex
            const updatedCategories = [...this.localCategoryList];
            updatedCategories.splice(index, 1);
            this.localCategoryList = updatedCategories;
            this.hasChanges = true;
          }
        },
      });
    },

    editCategory(index) {
      // 获取要编辑的分类
      const categoryToEdit = this.localCategoryList[index];

      // 设置编辑状态
      this.isEditing = true;
      this.editingIndex = index;
      this.isAddingNew = true;

      // 填充表单数据
      this.newCategoryName = categoryToEdit.text;

      // 找到并选择当前图标
      const iconIndex = this.availableIcons.findIndex(
        (icon) => icon === categoryToEdit.icon
      );
      this.selectedIconIndex = iconIndex >= 0 ? iconIndex : 0;
      
      // 添加滚动功能，将编辑项滚动到视图中适当位置
      this.$nextTick(() => {
        // 给DOM一点时间更新，确保编辑表单已渲染
        setTimeout(() => {
          // 使用ID选择器精确定位元素
          const query = uni.createSelectorQuery().in(this);
          
          // 获取视窗高度
          const systemInfo = uni.getSystemInfoSync();
          const windowHeight = systemInfo.windowHeight;
          
          // 查询分类项位置
          query.select(`#category-item-${index}`).boundingClientRect(itemData => {
            if (itemData) {
              // 将分类项滚动到顶部位置
              const scrollToPosition = Math.max(0, itemData.top - 20);
              
              uni.pageScrollTo({
                scrollTop: scrollToPosition,
                duration: 300
              });
              
              console.log(`滚动到分类项位置: ${scrollToPosition}px`);
            }
          }).exec();
        }, 50);
      });
    },

    startAddNew() {
      this.isAddingNew = true;
      this.newCategoryName = "";
      this.selectedIconIndex = 0;
      this.isEditing = false;
      this.editingIndex = -1;
    },

    cancelAdd() {
      this.isAddingNew = false;
      this.newCategoryName = "";
      this.isEditing = false;
      this.editingIndex = -1;
    },

    selectIcon(idx) {
      this.selectedIconIndex = idx;
    },

    confirmAdd() {
      
      if (!this.newCategoryName.trim()) {
        uni.showToast({
          title: "分类名称不能为空",
          icon: "none",
        });
        return;
      }

      // 使用选择的图标
      const iconName = this.availableIcons[this.selectedIconIndex];

      if (this.isEditing && this.editingIndex >= 0) {
        // 更新已有分类
        const updatedCategories = [...this.localCategoryList];
        const currentCategory = updatedCategories[this.editingIndex];
        const updatedCategory = {
          ...currentCategory,
          text: this.newCategoryName.trim(),
          icon: iconName,
          iconPath: this.getIconPath(iconName),
          // 保留protected和fixed属性
          protected: currentCategory.protected || false,
          fixed: currentCategory.fixed || false,
        };

        updatedCategories.splice(this.editingIndex, 1, updatedCategory);
        this.localCategoryList = updatedCategories;

        uni.showToast({
          title: "修改成功",
          icon: "success",
        });
      } else {
        // 添加新分类
        const newCategory = {
          id: `category_${Date.now()}`,
          text: this.newCategoryName.trim(),
          icon: iconName,
          iconPath: this.getIconPath(iconName),
          protected: false,
          fixed: false,
        };
        // 使用展开运算符创建新数组
        const newCategories = [...this.localCategoryList];
        newCategories.push(newCategory);

        // 确保使用一个全新的数组引用
        this.localCategoryList = newCategories;

        uni.showToast({
          title: "添加成功",
          icon: "success",
        });
      }

      // 重置状态
      this.isAddingNew = false;
      this.newCategoryName = "";
      this.isEditing = false;
      this.editingIndex = -1;
      this.hasChanges = true;
    },

    handleInputBlur() {
      // 可以选择在输入框失焦时自动确认或取消
    },

    // 拖拽排序相关方法
    onDragStart(event, index) {
      // 忽略固定项
      if (this.localCategoryList[index].fixed) return;

      this.dragIndex = index;
      this.dragStartY = event.touches[0].pageY;

      // 获取项目高度（这里使用固定值，可以根据实际情况调整）
      this.itemHeight = uni.upx2px(120); // 120rpx 转换为 px

      // 阻止默认行为和冒泡
      event.stopPropagation();
    },

    onDragMove(event) {
      if (this.dragIndex < 0) return;

      const currentY = event.touches[0].pageY;
      const moveDistance = currentY - this.dragStartY;
      this.dragCurrentY = moveDistance;

      // 计算移动的项目数
      const moveItems = Math.round(moveDistance / this.itemHeight);

      if (moveItems !== 0) {
        let targetIndex = this.dragIndex + moveItems;

        // 边界检查，避免移出数组范围
        targetIndex = Math.max(
          1,
          Math.min(targetIndex, this.localCategoryList.length - 1)
        );
        // 起始为1是为了避开固定项(通常是第0项)

        // 避免移动到固定项
        if (
          !this.localCategoryList[targetIndex].fixed &&
          targetIndex !== this.dragIndex
        ) {
          // 创建新的分类数组进行交换
          const updatedCategories = [...this.localCategoryList];
          const temp = updatedCategories[this.dragIndex];
          updatedCategories.splice(this.dragIndex, 1);
          updatedCategories.splice(targetIndex, 0, temp);

          // 更新当前拖拽索引
          this.dragIndex = targetIndex;
          this.dragStartY = currentY;
          this.dragCurrentY = 0;
          this.hasChanges = true;

          // 更新分类数组
          this.localCategoryList = updatedCategories;
        }
      }

      // 阻止默认行为和冒泡
      event.preventDefault();
      event.stopPropagation();
    },

    onDragEnd() {
      this.dragIndex = -1;
      this.dragCurrentY = 0;
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  position: relative;
}

.content-area {
  flex: 1;
  padding-bottom: 120rpx; /* 为底部操作栏留出空间 */
}

/* 分类列表 */
.category-list {
  background-color: #fff;
  margin: 30rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.category-item {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fff;
  position: relative;
  height: auto;
  min-height: 80rpx;
}

.category-item.fixed {
  color: #333;
}

.category-item.protected:not(.fixed) {
  position: relative;
}

.category-item.protected:not(.fixed)::after {
  content: "默认";
  position: absolute;
  right: 120rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 24rpx;
  color: #999;
  padding: 4rpx 10rpx;
  background-color: #f5f5f5;
  border-radius: 6rpx;
}

.category-item.dragging {
  background-color: #f6f9ff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.category-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.category-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
  text-align: center;
  line-height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0; /* 防止图标被压缩 */
}

.category-text {
  flex: 1;
  font-size: 32rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.drag-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 36rpx;
  flex-shrink: 0; /* 防止图标被压缩 */
}

.drag-handle {
  display: inline-block;
  transform: rotate(90deg);
}

.edit-btn-small {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4e6ef2;
  font-size: 32rpx;
  margin-right: 15rpx;
  position: relative;
}

.edit-icon {
  display: inline-block;
  transform: scale(-1, 1); /* 水平翻转 */
}

.btn-delete {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff4d4f;
  font-size: 36rpx;
  position: relative;
}

.action-buttons {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  flex-shrink: 0; /* 防止按钮被压缩 */
}

.edit-btn-small {
  width: 46rpx;
  height: 46rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4e6ef2;
  font-size: 32rpx;
  margin-right: 15rpx;
}

/* 内联编辑表单 */
.inline-edit-form {
  background-color: #f8f9ff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-top: -1rpx; /* 抵消前一个元素的bottom border */
}

/* 添加分类区域 */
.add-category {
  margin: 30rpx;
}

.btn-add {
  display: flex;
  align-items: center;
  color: #4e6ef2;
  font-size: 32rpx;
  background-color: #fff;
  padding: 30rpx;
  border-radius: 12rpx;
  border: 2rpx dashed #4e6ef2;
  justify-content: center;
  margin-top: 30rpx;
}

.add-icon {
  margin-right: 10rpx;
  font-size: 36rpx;
  font-weight: bold;
}

.add-form {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.category-input {
  height: 80rpx;
  border-bottom: 1rpx solid #eee;
  padding: 0 20rpx;
  font-size: 32rpx;
  margin-bottom: 30rpx;
}

/* 图标选择器 */
.icon-selector {
  margin-bottom: 30rpx;
}

.selector-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: block;
}

.icon-grid {
  display: flex;
  flex-wrap: wrap;
}

.icon-item {
  width: 80rpx;
  height: 80rpx;
  margin: 10rpx;
  border-radius: 12rpx;
  background-color: #f6f8ff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.icon-item.selected {
  background-color: #e6ecff;
  border: 2rpx solid #4e6ef2;
}

.icon-item.selected::after {
  content: "";
  position: absolute;
  right: -8rpx;
  top: -8rpx;
  width: 24rpx;
  height: 24rpx;
  background-color: #4e6ef2;
  border-radius: 50%;
}

.icon-item image {
  width: 50rpx;
  height: 50rpx;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  .btn-cancel,
  .btn-confirm {
    padding: 20rpx 30rpx;
    font-size: 30rpx;
    text-align: center;
    min-width: 120rpx;
    border-radius: 8rpx;
  }

  .btn-cancel {
    color: #999;
    margin-right: 20rpx;
    background-color: #f5f5f5;
  }
  .btn-confirm {
  color: #4e6ef2;
  background-color: #e6ecff;
}
}



/* 提示信息 */
.tip-section {
  margin: 40rpx 30rpx;
  background-color: #f6f8ff;
  padding: 20rpx;
  border-radius: 10rpx;
}

.tip-text {
  font-size: 26rpx;
  color: #999;
  line-height: 1.5;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  padding: 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.bottom-bar .action-buttons {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 700rpx; /* 限制最大宽度 */
  margin-left: 0;
}

.bottom-btn {
  border-radius: 40rpx !important;
  min-width: 320rpx;
  margin: 0 10rpx;
  // height: 100rpx !important;
  // border: none !important;
  overflow: hidden;
}

// 自定义底部按钮颜色
:deep(.btn-secondary) {
  background-color: #f5f5f5 !important;
  color: #666 !important;
}

:deep(.btn-primary) {
  background-color: #4e6ef2 !important;
  color: #fff !important;
}
</style> 